package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustomException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import com.heima.utils.common.IdCardUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper,ApUserRealname> implements ApUserRealnameService {

    @Resource
    private ApUserMapper apUserMapper;

    @Resource
    WemediaFeign wemediaFeign;

    @Resource
    ArticleFeign articleFeign;

    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        dto.checkParam();

        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<ApUserRealname> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> result = page(page, lambdaQueryWrapper);

        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) result.getTotal());

        responseResult.setData(result.getRecords());

        return responseResult;
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        if (dto == null || dto.getId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUserRealname apUserRealname = getById(dto.getId());
        if (apUserRealname == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        if (apUserRealname.getStatus().intValue() != 1) {
            throw new CustomException(AppHttpCodeEnum.DATA_STATUS_ERROR);
        }

        ApUser apUser = apUserMapper.selectById(apUserRealname.getId());
        if (apUser == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "关联数据不存在");
        }
        apUserRealname.setStatus(status);
        apUserRealname.setCreatedTime(new Date());
        if (StringUtils.isNotBlank(dto.getMsg())) {
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);
        if (status.intValue() == AdminConstants.AD_USER_ISSTATUS) {
            WmUser wmUser = createWmUser(dto, apUser);
            if (wmUser == null) {
                throw new CustomException(AppHttpCodeEnum.SERVER_ERROR, "创建自媒体用户失败");
            }
            createAuthor(wmUser);
        }
        apUser.setFlag((short) 1);
        apUser.setIdentityAuthentication(true);
        apUserMapper.insert(apUser);
        return ResponseResult.okResult();
    }


    private WmUser createWmUser(AuthDto dto, ApUser apUser) {
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        if (wmUser != null) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST, "用户数据已存在");
        }
         wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(AdminConstants.AD_USER_ISSTATUS);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        return wemediaFeign.save(wmUser);
    }

    private void createAuthor(WmUser wmUser) {
        ApAuthor byUserId = articleFeign.findByUserId(wmUser.getApUserId());
        if (byUserId != null) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST, "作者数据已存在");
        }
        ApAuthor author = new ApAuthor();
        author.setName(wmUser.getName());
        author.setType(2);
        author.setUserId(wmUser.getApUserId());
        author.setCreatedTime(new Date());
        author.setWmUserId(wmUser.getId());
        articleFeign.save(author);
    }

    private void createWmUserAndAuthor(AuthDto dto) {
        ApUserRealname aur = getById(dto.getId());
        // 调用公安部实名认证接口，识别该用户身份信息是否正确
        boolean checkIdcard = IdCardUtils.checkIdCardInfo(aur.getRealName(), aur.getIdno());
        if (!checkIdcard) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID, "用户身份证信息错误");
        }
    }
}
